﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
 
using Teigha.Core;
using Teigha.TD;
using Autodesk.Revit.DB;
//using BinLibrary.WinHelper;
//using RevitReadAutoCAD.TeighaHelper.CadModels;

namespace YJKCopyModel.Basic
{
    public class Utils
    {
        private static Utils instance;

        public static Utils Instance 
        {
            get
            {
                if (instance==null)
                {
                    instance= new Utils();
                }
                return instance;
            }
        }
        static Utils()
        {
            AppDomain.CurrentDomain.AssemblyResolve += Onassemblyresolve;
        }

        private static Assembly Onassemblyresolve(object sender, ResolveEventArgs args)
        {

            //LogHelper.LogWrite(@"c:\lackofdlls.txt", "argsName is :" + args.Name);

            //var path1 = @"C:\Users\XU\source\repos\RevitReadAutoCAD\RevitReadAutoCAD\dlls\HYTD";
            var path2 = @"C:\Hongye\HYRME2018\Bin";
            var searches = new List<string>();
            
            searches.Add(path2);
            //MessageBox.Show("resolving");

            var assemblyName = new AssemblyName(args.Name);

            foreach (var item in searches)
            {
                var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));
                //MessageBox.Show(file);

                if (File.Exists(file))
                {
                    return Assembly.LoadFile(file);
                }
            }

            return args.RequestingAssembly;
         
        }

        //public static List<HelloWorldReadCAD.CADTextModel> GetCADTextInfl(string dwgfile)
        //{

        //    var result = new List<HelloWorldReadCAD.CADTextModel>();

        //    TeighaServices.TeighaServicesInstance.InitTeighaService(true);

        //    OdDbDatabase database = OdDbDatabase.createObject();
        //    database.readFile(dwgfile);

        //    using (OdDbBlockTable blocktable = (OdDbBlockTable)database.getBlockTableId().safeOpenObject(OpenMode.kForRead))
        //    {
        //        using (OdDbSymbolTableIterator enumerator = blocktable.newIterator())
        //        {
        //            //如何移动指针到开始

        //            enumerator.start();
        //            StringBuilder sb = new StringBuilder();
        //            while (!enumerator.done())
        //            {
        //                using (OdDbBlockTableRecord record = (OdDbBlockTableRecord)enumerator.getRecord())
        //                {
        //                    //OdResBuf odresbuf = OdResBuf.newRb(0,"Line");

        //                    foreach (var oddbblock in record.getBlockReferenceIds())
        //                    {

        //                    }
        //                }
        //                enumerator.step();
        //            }
        //        }
        //    }




        //    database.Dispose();

        //    TeighaServices.TeighaServicesInstance.InitTeighaService(false);

        //    return result;
        //}

        /// <summary>
        /// 通过hostappserivice 读取文件
        /// </summary>
        /// <param name="dwgfile"></param>
        /// <returns></returns>
        public static void GetCADTextInfl1(string dwgfile, string objecttype = "line")
        {
            //var result = new List<CadModels.CADMText>();
            //var result1 = new List<CadModels.CadMLine>();
            
            TeighaServices.TeighaServicesInstance.InitTeighaService(true);
            //ExHostAppServices hostappser = TeighaServices.TeighaServicesInstance.HostAppServices;

            //hostappser.readFile(dwgfile);
            MessageBox.Show("beforeRead");
            var database = TeighaServices.TeighaServicesInstance.HostAppServices.readFile(dwgfile);

            OdDbObjectId idEnt = OdDbObjectId.kNull;


            #region newmethod

            //var services = new ExSystemServices();
            //TD_Db.odInitialize(services);

            //var appservices = new ExHostAppServices();

            //appservices.readFile(dwgfile);
            
            #endregion
             
            //OdDbDatabase database = OdDbDatabase.createObject();
            //database.readFile(dwgfile);

            //database.readFile(dwgfile);
            OdResBufTypesEnum buftypes = new OdResBufTypesEnum();

            var lineIdArray = OdDbSelectionSet.@select(database, new OdResBufTypesEnum().LINE).objectIdArray();
            var insertIdArray = OdDbSelectionSet.@select(database, new OdResBufTypesEnum().INSERT).objectIdArray();
            var circleIdArray = OdDbSelectionSet.@select(database, new OdResBufTypesEnum().CIRCLE).objectIdArray();
            var polylineIdArray = OdDbSelectionSet.@select(database, new OdResBufTypesEnum().POLYLINE).objectIdArray();
            var textIdArray = OdDbSelectionSet.@select(database, new OdResBufTypesEnum().TEXT).objectIdArray();

             
            #region dimed

            //using (
            //    OdDbBlockTable blocktable =
            //        (OdDbBlockTable) database.getBlockTableId().safeOpenObject(OpenMode.kForRead))
            //{
            //    using (OdDbSymbolTableIterator enumerator = blocktable.newIterator())
            //    {
            //        //如何移动指针到开始

            //        enumerator.start();
            //        StringBuilder sb = new StringBuilder();
            //        while (!enumerator.done())
            //        {
            //            using (OdDbBlockTableRecord record = (OdDbBlockTableRecord) enumerator.getRecord())
            //            {
            //                //OdResBuf odresbuf = OdResBuf.newRb(0,"Line");

            //                foreach (var oddbblock in record.getBlockReferenceIds())
            //                {

            //                }
            //            }
            //            enumerator.step();
            //        }
            //    }
            //}

            #endregion

            //MessageBox.Show("after read" + "count:" + lineIdArray.Count.ToString());

            int a = 0;

            foreach (OdDbObjectId current2 in lineIdArray)
            {
                OdDbLine arg_21E_0 = (OdDbLine)current2.openObject(OpenMode.kForRead);
                OdGePoint3d odGePoint3d3 = new OdGePoint3d();
                OdGePoint3d odGePoint3d4 = new OdGePoint3d();
                XYZ xYZ3 = new XYZ();
                XYZ xYZ4 = new XYZ();


                arg_21E_0.getStartPoint(odGePoint3d3);
                arg_21E_0.getEndPoint(odGePoint3d4);

                xYZ3 = odGePoint3d3.ToXYZ();// new XYZ(odGePoint3d3.x, odGePoint3d3.y, XYZ.Zero.Z);
                xYZ4 = odGePoint3d4.ToXYZ();//new XYZ(odGePoint3d4.x, odGePoint3d4.y, XYZ.Zero.Z);
                //result1.Add(new CadMLine() {Startpoint = xYZ3, EndPoint = xYZ4});

                //MessageBox.Show(result1.ElementAt(a).Length.ToString());
                //LogHelper.LogWrite(@"c:\lengths.txt", result1.ElementAt(a).Length.ToString());

                //if (this.useXYZComparer.GetHashCode(xYZ3) != this.useXYZComparer.GetHashCode(xYZ4))
                //{
                //    PipeCADElement pipeCADElement3 = new PipeCADElement(xYZ3, xYZ4);
                //    if (this.IsContainsObjectId(current2))
                //    {
                //        pipeCADElement3.BIsMainPipe = true;
                //    }
                //    this.m_CADData.LstAllPipe.Add(pipeCADElement3);
                //}
                a++;
                if (a > 120) break;
            }
             
            database.Dispose();

            TeighaServices.TeighaServicesInstance.InitTeighaService(false);

            //return result;
        }

        /// <summary>
        /// 获取块
        /// </summary>
        /// <param name="oddbRef"></param>
        /// <param name="mtrTrans"></param>
        /// <param name="nDeepth"></param>
        /// <param name="lstLines"></param>
        /// <param name="lstBlocks"></param>
        /// <param name="lstPolylines"></param>
        private static void GetEntitisByBlock(OdDbBlockReference oddbRef, OdGeMatrix3d mtrTrans, int nDeepth,
            out List<OdDbLine> lstLines, out List<OdDbBlockReference> lstBlocks, out List<List<OdDbLine>> lstPolylines)
        {
            lstLines = new List<OdDbLine>();
            lstBlocks = new List<OdDbBlockReference>();
            lstPolylines = new List<List<OdDbLine>>();
            try
            {
                OdDbObjectIterator odDbObjectIterator =
                    ((OdDbBlockTableRecord)oddbRef.blockTableRecord().openObject(OpenMode.kForRead)).newIterator();
                odDbObjectIterator.start();
                while (!odDbObjectIterator.done())
                {
                    OdDbEntity odDbEntity = odDbObjectIterator.entity(OpenMode.kForRead, false);
                    if (odDbEntity != null)
                    {
                        //this.GroupEntity(odDbEntity, mtrTrans, nDeepth, ref lstLines, ref lstBlocks, ref lstPolylines,
                        //    ref this.m_lstTextInfo);
                    }
                    odDbObjectIterator.step();
                }
                
            }
            catch
            {
            }
        }
    }


}
